﻿
using System.Text.RegularExpressions;

namespace 正则Replace
{
    /// <summary>
    /// 
    /// </summary>
    public static class QueryValidation
    {
        #region Constants

        /// <summary>
        /// Qualifier delimiter start
        /// </summary>
        public const string QualifierDelimiter = @"\";

        /// <summary>
        /// Regex pattern for checking excess white spaces
        /// </summary>
        public const string ExcessWhitespacePattern = @"\s\s+";

        /// <summary>
        /// Single white space string
        /// </summary>
        public const string SingleSpaceString = " ";

        #endregion Constants


        #region Fields

        /// <summary>
        /// 
        /// </summary>
        private static readonly Regex ExcessWhitespaceRegex = new Regex(ExcessWhitespacePattern);

        #endregion Fields


        /// <summary>
        /// Get qualifier from 
        /// </summary>
        /// <param name="queryInput">Query input</param>
        /// <returns>Return search qualifier if found else NULL</returns>
        public static string GetSearchQualifierFromQuery(string queryInput)
        {
            //// Check if null or empty & remove excess white spaces
            var query = queryInput?.Trim();
            query = ExcessWhitespaceRegex.Replace(query, SingleSpaceString);

            //// Get qualifier & check
            var qualifier = query.Split()?[0];

            return !string.IsNullOrEmpty(qualifier) && qualifier.StartsWith(QualifierDelimiter) ?
                qualifier : null;
        }
    }
}
